package com.chuangshu.chuangshuteam.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chuangshu.chuangshuteam.config.BaseContext;
import com.chuangshu.chuangshuteam.dto.CompetitionsDTO;
import com.chuangshu.chuangshuteam.dto.Result;
import com.chuangshu.chuangshuteam.entity.Competitions;
import com.chuangshu.chuangshuteam.service.CompetitionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;

@Slf4j
@RestController
@RequestMapping("/competition")
public class CompetitionController {

    @Autowired
    private CompetitionService competitionService;

    /**
     * 添加比赛信息
     * @param competitionsDTO 比赛信息DTO
     * @return 添加结果
     */

    @PostMapping
    public Result addCompetition(@RequestBody CompetitionsDTO competitionsDTO) {
        // 补充创建者信息
        competitionsDTO.setCreatedBy(BaseContext.getCurrentId());

        // 调用服务层添加比赛信息
        boolean isSaved = competitionService.saveCompetition(competitionsDTO);

        if (isSaved) {
            return Result.ok("比赛信息添加成功");
        } else {
            return Result.fail("比赛信息添加失败");
        }
    }

    /**
     * 根据ID查询比赛信息
     * @param id 比赛ID
     * @return 比赛信息
     */
    @GetMapping("/{id}")
    public Result getCompetitionById(@PathVariable Long id) {
        Competitions competition = competitionService.getById(id);
        if (competition != null) {
            return Result.ok(competition);
        } else {
            return Result.fail("未找到该比赛信息");
        }
    }

    /**
     * 查询比赛信息列表（分页）
     * @param page 页码
     * @param pageSize 每页大小
     * @param name 比赛名称（可选）
     * @param organizer 主办方（可选）
     * @param startDate 开始日期（可选）
     * @param endDate 结束日期（可选）
     * @return 比赛信息列表
     */
    @GetMapping("/page")
    public Result getCompetitionPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String organizer,
            @RequestParam(required = false) LocalDate startDate,
            @RequestParam(required = false) LocalDate endDate) {

        // 构造分页对象
        Page<Competitions> pageInfo = new Page<>(page, pageSize);

        // 构造查询条件
        LambdaQueryWrapper<Competitions> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null, Competitions::getName, name)
                .like(organizer != null, Competitions::getOrganizer, organizer);

        if (startDate != null && endDate != null) {
            queryWrapper.between(Competitions::getDate, startDate, endDate);
        } else if (startDate != null) {
            queryWrapper.ge(Competitions::getDate, startDate);
        } else if (endDate != null) {
            queryWrapper.le(Competitions::getDate, endDate);
        }

        queryWrapper.orderByDesc(Competitions::getCreatedAt);

        // 执行分页查询
        competitionService.page(pageInfo, queryWrapper);

        return Result.ok(pageInfo.getRecords(), pageInfo.getTotal());
    }

    /**
     * 更新比赛信息
     * @param id 比赛ID
     * @param competitionsDTO 比赛信息DTO
     * @return 更新结果
     */
    @PutMapping("/{id}")
    public Result updateCompetition(@PathVariable Long id, @RequestBody CompetitionsDTO competitionsDTO) {
        boolean isUpdated = competitionService.updateCompetition(id, competitionsDTO);
        if (isUpdated) {
            return Result.ok("比赛信息更新成功");
        } else {
            return Result.fail("比赛信息更新失败");
        }
    }

    /**
     * 删除比赛信息
     * @param id 比赛ID
     * @return 删除结果
     */
    @DeleteMapping("/{id}")
    public Result deleteCompetition(@PathVariable Long id) {
        boolean isRemoved = competitionService.removeById(id);
        if (isRemoved) {
            return Result.ok("比赛信息删除成功");
        } else {
            return Result.fail("比赛信息删除失败");
        }
    }
}